﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FSViet.Survey.Helpers;
using System.Web.UI.HtmlControls;

namespace FSViet.Survey.Administration.Report
{
	public partial class Comment : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			string answerId, campaignId, questionId;
			int page = 1;
			answerId = Request.QueryString["AnswerId"] ?? "";
			campaignId = Request.QueryString["CampaignId"] ?? "";
			questionId = Request.QueryString["QuestionId"] ?? "";
			try
			{
				page = Convert.ToInt32(Request.QueryString["p"] ?? "0");
			}
			catch
			{
			}
			try
			{
				LoadData(page, campaignId, questionId, answerId);
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString().Replace("\r\n", "<br/>");
#endif
			}
		}

		void LoadData(int page, string campaignId, string questionId, string answerId)
		{
			DataHelper dataH = new DataHelper();
			page = page - 1;
			if (page < 0) page = 0;
			try
			{
					int totalRecord = 0;
					var data = dataH.Load(
						"SELECT COUNT(*) FROM Questions WHERE CampaignId=@CampaignId AND IsAnswerGroup=@IsAnswerGroup",
						"SELECT * FROM Questions WHERE CampaignId=@CampaignId AND IsAnswerGroup=@IsAnswerGroup",
						page * GlobalApplication.ItemPerPage,
						GlobalApplication.ItemPerPage,
						out totalRecord,
						dataH.CreateParam("CampaignId", System.Data.SqlDbType.Char, campaignId),
						dataH.CreateParam("QuestionId", System.Data.SqlDbType.Char, questionId),
						dataH.CreateParam("AswerId", System.Data.SqlDbType.Char, answerId));

					ShowPage(page,totalRecord, campaignId, questionId, answerId);

					ListItem.DataSource = data;
					ListItem.DataBind();
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		void ShowPage(int currentPage,int totalRecord, string campaignId, string questionId, string answerId)
		{
			if (totalRecord > GlobalApplication.ItemPerPage)
			{ }
			else
			{
				PageList.Visible = false;
				return;
			}

			int totalPage = totalRecord / GlobalApplication.ItemPerPage + 1;
			var ul = new HtmlGenericControl("ul");
			for (int i = 1; i <= totalPage; i++)
			{
				var li = new HtmlGenericControl("li");
				if (i == currentPage)
					li.Controls.Add(new HyperLink() { Text = i.ToString(), NavigateUrl = "#" });
				else
					li.Controls.Add(new HyperLink() { Text = i.ToString(), NavigateUrl = string.Format("?CampaignId={0}&QuestionId={1}&AnswerId={2}&p={3}", campaignId, questionId, answerId) });
				ul.Controls.Add(li);
			}
			PageList.Controls.Add(ul);
		}
	}
}